//
//  CLReadModel.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/22.
//

#import "CLReadModel.h"
#import "CLBook.h"
#import <objc/runtime.h>
#import <YYKit/YYClassInfo.h>
#import "CLKeyedArchiver.h"
@implementation CLReadModel
@synthesize bookName = _bookName;

- (instancetype)init
{
    self = [super init];
    if (self) {
        _markModels = [NSMutableArray array];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
//        _bookid = [aDecoder decodeObjectForKey:@"bookid"];
        _bookName = [aDecoder decodeObjectForKey:@"bookName"];
        _bookSourceType = [aDecoder decodeInt64ForKey:@"bookSourceType"];
        _chapterListModels = [aDecoder decodeObjectForKey:@"chapterListModels"];
        _markModels = [aDecoder decodeObjectForKey:@"markModels"];
        _fullText = [aDecoder decodeObjectForKey:@"fullText"];
        _ranges = [aDecoder decodeObjectForKey:@"ranges"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    if (_bookName) {
        [aCoder encodeObject:_bookName forKey:@"bookName"];
    }
    
    [aCoder encodeInt64:_bookSourceType forKey:@"bookSourceType"];
    
    if (_chapterListModels && _chapterListModels.count) {
        [aCoder encodeObject:_chapterListModels forKey:@"chapterListModels"];
    }
    
    if (_markModels && _markModels.count) {
        [aCoder encodeObject:_markModels forKey:@"markModels"];
    }
    
    if (_fullText) {
        [aCoder encodeObject:_fullText forKey:@"fullText"];
    }
    
    if (_ranges) {
        [aCoder encodeObject:_ranges forKey:@"ranges"];
    }
}

// MARK: 辅助

/// 保存
- (void)save {
    
    [self.recordModel save];
    [CLKeyedArchiver archiver:self.bookid fileName:CL_READ_KEY_OBJECT object:self];
}

/// 是否存在阅读对象
+ (BOOL)isExist:(NSString *)bookid {
    return [CLKeyedArchiver isExist:bookid fileName:CL_READ_KEY_OBJECT];
}


// MARK: 构造

/// 获取阅读对象,如果则创建对象返回
+ (CLReadModel *)model:(NSString *)bookid {
    
    CLReadModel *readModel = nil;
    
    if ([CLReadModel isExist:bookid]) {
        
        readModel = [CLKeyedArchiver unarchiver:bookid fileName:CL_READ_KEY_OBJECT];
        
    }else{
        
        readModel = [[CLReadModel alloc]init];
    }
    
    // 获取阅读记录
    readModel.bookid = bookid;
    readModel.recordModel = [CLReadRecordModel model:bookid];
    return readModel;
}

- (void)setBookName:(NSString *)bookName {
    _bookName = bookName;
    self.title = bookName;
}

- (NSString *)bookName {
    return StrNilHolder(_bookName, self.title);
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}
@end
